#include "Packer.h"


Packer::Packer()
{
	packedData = Queue<unsigned char>();
	package = 0x00;
	currentUnpackedBit = 0;
	totalPackedBits = 0;
}

bool Packer::empty()
{
	return packedData.empty();
}

void Packer::finish()
{
	//just adds the last package to the packedData.
	totalPackedBits = totalPackedBits + currentUnpackedBit;
	if(currentUnpackedBit != 0) //I have to add the last package.	
	{
		packedData.push(package);
	}
}

void Packer::pack(BitArray array)
{
	int i = 0;
	for(i = 0; i < array.size(); i++)
	{
		if(currentUnpackedBit == 8)
		{
			currentUnpackedBit = 0;
			packedData.push(package); //add the package to the array.
			package = 0x00;//empty the package
		}
		//add a bit to the data from the array
		package = SetBit(package, currentUnpackedBit, array[i].getBit());
		//increment the unpacked bits.
		currentUnpackedBit++;
	}	
}

unsigned char Packer::get(unsigned char& packedCount)
{
	unsigned char value = 0;
	if(totalPackedBits == 0)
	{
		packedCount = 0;
		value = 0;
		return value;
	}
	else
	{
		if(totalPackedBits < 8)
		{
			packedCount = totalPackedBits;
			totalPackedBits = 0;
			value = packedData.pop();
		}
		else
		{
			packedCount = 8;
			totalPackedBits = totalPackedBits - 8;
			value = packedData.pop();
		}
		return value;
	}
}


